package com.code2roc.jarmanage.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.logging.*;

public class LogUtil {

    private static final Logger logger = Logger.getLogger("");

    public static Logger getLogger() {
        String logDirPath = "logs" + File.separator;
        File logDir = new File(logDirPath);
        if (!logDir.exists()) {
            logDir.mkdir();
        }
        String logPath = logDirPath + CommonUtil.getDateFormatToDay() + ".log";
        if (!Files.exists(Paths.get(logPath)) || logger.getHandlers().length == 0) {
            init(logPath);
        }
        return logger;
    }

    private static void init(String logPath) {
        try {
            for (Handler handler : logger.getHandlers()) {
                if(handler.getClass()!=ConsoleHandler.class){
                    handler.close();
                    logger.removeHandler(handler);
                }
            }

            logger.setLevel(Level.INFO);
            FileHandler handler = new FileHandler(logPath, true);
            SimpleFormatter formatter = new SimpleFormatter();
            handler.setFormatter(formatter);
            handler.setLevel(Level.INFO);
            handler.setEncoding("utf-8");
            logger.addHandler(handler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void error(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        getLogger().warning(sw.toString());
    }

    public static void error(String foramt,Object ... arguments) {
        getLogger().warning(MessageFormat.format(foramt,arguments));
    }

    public static void info(String message) {
        getLogger().info(message);
    }
}
